<template>
  <div class="container">
    <Navbars ></Navbars>
    <!-- 条件 -->
    <div class="querydiv" shadow="never">
      <el-form :inline="true" size="medium" label-width="70px">
        <el-form-item label="信息查询">
          <el-select-tree popper-class="stafftree" :popper-append-to-body="false"
              clearable style="width:100%" :highlight-current="true" 
              :props="defaultProps" 
              :default-expand-all="false" placeholder="请选择机构" :data="OrganList" :show-checkbox="true" :check-strictly="true"
              v-model="listQuery.orgId" 
          ></el-select-tree>
        </el-form-item>
        <el-form-item>
          <el-input v-model="listQuery.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="listQuery.mobile" placeholder="手机号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="btn btncolor" type="primary" @click="getList">查询</el-button>
          <el-button class="btn" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="mt15">
      <el-card class="tab-card" shadow="never">
        <div slot="header" class="spacebetween disflex align-center">
          <span style="color:#676a6f;font-size:14px">用户管理列表</span>
          <el-button class="btn btncolor" icon="el-icon-plus" type="primary" @click="handleAdd">新增</el-button>
        </div>
        <el-table :data="tableData" :header-cell-style="{background:'#e4ebfd',color:'#7690db'}" :row-class-name="tableRowClassName">
            <el-table-column align="center" prop="orgName" label="	所属机构"></el-table-column>
            <el-table-column align="center" prop="username"  label="用户名" ></el-table-column>
            <el-table-column align="center" prop="name" label="姓名"></el-table-column>
            <el-table-column align="center" prop="mobile" label="手机号"></el-table-column>
            <el-table-column align="center" prop="status" label="状态"></el-table-column>
            <el-table-column align="center" fixed="right"  label="操作">
              <template slot-scope="scope">
                <el-button type="text"  class="edit" @click="handlEdit(scope.row)">编辑</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button type="text" @click="handleRules(scope.row)">分配角色</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button type="text" @click="handleDel(scope.row)" class="del">删除</el-button>
              </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!--分页 -->
      <Pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.num"></Pagination>
    </div>
    <!-- 新增修改 -->
    <el-dialog :title="title" :visible.sync="isvisible" width="40%" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="80px">
        <el-form-item label="上级机构" prop="orgId">
            <el-select-tree popper-class="stafftree" :popper-append-to-body="false"
                clearable style="width:100%" :highlight-current="true" 
                :props="defaultProps" 
                :default-expand-all="false" placeholder="请选择机构" :data="OrganList" :show-checkbox="true" :check-strictly="true"
                v-model="addForm.orgId" 
            ></el-select-tree>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" >
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password1">
          <el-input v-model="addForm.password1"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="addForm.status" size="small">
            <el-radio-button v-for="(item,index) in statuslist" :key="index" :label="item.code">{{item.name}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitAdd('addForm')" class="btncolor" size="small" :loading="loading" :disabled="loading">确定创建</el-button>
          <el-button @click="isvisible = false" size="small">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配角色 -->
    <el-dialog title="分配角色" :visible.sync="rolevisible" width="40%" :close-on-click-modal="false">
      <el-form label-width="80px">
        <el-form-item label="分配角色" prop="name">
          <el-select v-model="roleform.roleId" multiple  placeholder="选择角色" style="width:80%">
            <el-option v-for="(item,index) in roleList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitrole" class="btncolor" size="small" :loading="loading" :disabled="loading">确定</el-button>
          <el-button @click="rolevisible = false" size="small">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { dicttype } from "@/api/role.js";
import {roleList} from "@/api/role.js";
import { userPage,useradd,userupdate,userdetail,userallocationl,usergetallocationl,userdel} from '@/api/user.js'
import { orgTree } from '@/api/organization.js'
import Pagination from '@/components/Pagination'
import {formatDataTree} from '@/utils/index'
export default {
  name: 'user',
  components: { Pagination },
  data() {
    return {
      total: 150,
      listLoading: true,
      loading:false,
      listQuery: {
        orgId:'',
        username:'',
        page: 1,
        num: 20
      },
      defaultProps: {
          parent: 'pid',   // 父级唯一标识
          value: 'id',          // 唯一标识
          label: 'name',       // 标签显示
          children: 'children', // 子级
      }, // 配置
      OrganList:[],
      tableData: [],
      isvisible:false,
      title:"新增用户",
      addForm:{

      },
      addRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        password1: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        orgId: [
          { required: true, message: '请选择机构', trigger: 'blur' },
        ]
      },
      statuslist:[],
      rolevisible:false,
      roleform:{
        userId:'',
        roleId:[]
      },
      roleList:[]
    }
  },
  created() {
    this.getList()
    this.getDIctyp()
    this.getorgTreeList()
  },
  methods: {
    // 设置表格颜色
    tableRowClassName({row, rowIndex}) {
      if (rowIndex%2==0) {
        return 'warning-row';
      }
      return '';
    },
    // 获取状态字典
    getDIctyp(){
      this.$getFlag().then(obj=>{
        dicttype({type:'role_status'},obj.data).then(res=>{
          if(res.status == 200){
            this.statuslist = res.data
            // this.addForm.status = res.data[0].code
          }
        })
      })
    },
    // 新增
    handleAdd() {
      this.addForm={}
      this.isvisible = true
      this.title = "新增用户"
    },
    // 新增修改确定
    onSubmitAdd(formName){
      if(!this.addForm.orgId){
        this.$notify({ title: "操作失败",message: "请选择机构", type: "error", duration: 2000,});
        return false
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.title == "新增用户"){
            this.$getFlag().then(obj=>{
              useradd(this.addForm,obj.data).then(res=>{
                if(res.status == 200){
                  this.$notify({  title: "操作成功", message: res.msg, type: "success",duration: 2000,});
                  this.getList()
                  this.isvisible = false
                }else{
                  this.$notify({ title: "操作失败",message: res.error, type: "error", duration: 2000,});
                }
              })
            })
          }else{
            this.$getFlag().then(obj=>{
              userupdate(this.addForm,obj.data).then(res=>{
                if(res.status == 200){
                  this.$notify({  title: "操作成功", message: res.msg, type: "success",duration: 2000,});
                  this.getList()
                  this.isvisible = false
                }else{
                  this.$notify({ title: "操作失败",message: res.error, type: "error", duration: 2000,});
                }
              })
            })
          }
        }
      })
    },
    //获取角色列表
    getroleList(){
      let data = {
        page:1,
        num:1000
      }
      this.$getFlag().then(obj=>{
        roleList(data,obj.data).then((response) => {
          this.roleList = response.list;
        });
      })
    },
    // 分配角色
    handleRules(row){
      this.getroleList()
      this.rolevisible = true
      this.roleform.userId = row.id
      this.$getFlag().then(obj=>{
        usergetallocationl({id:row.id},obj.data).then(res=>{
          if(res.status == 200){
            this.roleform.roleId = res.data
          }
        })
      })
    },  
    // 确定分配角色
    onSubmitrole(){
      this.$getFlag().then(obj=>{
        userallocationl(this.roleform,obj.data).then(res=>{
          if(res.status == 200){
            this.$notify({  title: "操作成功", message: res.msg, type: "success",duration: 2000,});
            this.rolevisible = false
          }else{
            this.$notify({ title: "操作失败",message: res.error, type: "error", duration: 2000,});
          }
        })
      })
      
    },
    // 获取表格列表信息
    getList() {
      this.$getFlag().then(obj=>{
        this.listLoading = false
        userPage(this.listQuery,obj.data).then(response => {
          this.tableData = response.list
          this.total = Number(response.total)
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      })
    },
    // 修改弹窗及获取用户详情
    handlEdit(row){
      this.isvisible = true
      this.title = "修改用户"
      this.$getFlag().then(obj=>{
        userdetail({id:row.id},obj.data).then(res=>{
          if(res.status == 200){
            this.addForm = res.data
            this.addForm.password = ""
          }
        })
      })
    },
    handleDel(row){
      this.$confirm('确定要删除吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(() => {
        this.$getFlag().then(obj=>{
          userdel({id:row.id},obj.data).then(res=>{
              if(res.status == 200){
                this.$notify({  title: "操作成功", message: res.msg, type: "success",duration: 2000,});
                this.getList()
              }else{
                this.$notify({ title: "操作失败",message: res.msg, type: "error", duration: 2000,});
              }
          })
        }) 
      })
      .catch(() => {});
    },
    // 获取查询条件机构
    getorgTreeList(){
      let formorg = {
        page:1,
        num:100,
        pid:'',
        name:'',
        code:''
      }
      this.OrganList = []
      this.$getFlag().then(obj=>{
        orgTree(formorg,obj.data).then(res=>{
          this.OrganList.push(formatDataTree(res.list))
        })
      })
    },
    //重置
    handleReset(){
      this.listQuery.orgId = ""
      this.listQuery.username = ""
      this.listQuery.mobile = ""
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .stafftree .el-tree-node__content .el-checkbox .el-checkbox__input {
  display: none;
}
.btn{
  width: 100px;
  padding:8px 20px
}

</style>
<style>
  .el-table .warning-row {
    background: #f6f9fe;
  }
</style>
